<template>
  <view class="consultation-page">
    <!-- 顶部导航栏 -->
    <view class="tab-bar">
      <text class="tab active">图文问诊</text>
    </view>

    <!-- 订单列表 -->
    <view class="order-list">
      <view v-for="order in orders" :key="order.orderId" class="order-item" @click="openOrder(order)">
        <image :src="order.doctorAvatar || '/static/doctor.png'" class="doctor-avatar"></image>
        <view class="order-content">
          <view class="doctor-info">
            <text class="doctor-name">{{ order.doctorName }} {{ order.doctorTitle }}</text>
            <text class="order-status" :class="getStatusClass(order.orderStatus)">
              {{ order.orderStatus }}
            </text>
          </view>
          <text class="order-description">{{ formatDescription(order.description) }}</text>
          <text class="order-time">{{ formatTime(order.consultationTime) }}</text>
        </view>
      </view>
    </view>

    <!-- 订单详情弹窗 -->
    <view v-if="showModal" class="order-modal">
      <view class="modal-content">
        <text class="modal-title">订单详情</text>
        <text>医生: {{ selectedOrder.doctorName }} ({{ selectedOrder.doctorTitle }})</text>
        <text>问题描述: {{ selectedOrder.description }}</text>
        <text>回答: {{ selectedOrder.answerContent }}</text>
        <text>订单状态: {{ selectedOrder.orderStatus }}</text>
        <text>下单时间: {{ formatTime(selectedOrder.consultationTime) }}</text>
        <text>支付方式: {{ selectedOrder.paymentMethod || '暂无' }}</text>
        <text>订单金额: ¥{{ selectedOrder.orderAmount }}</text>

        <!-- 如果订单状态是待支付，显示继续支付按钮 -->
        <button v-if="selectedOrder.orderStatus === '待支付'" class="pay-btn" @click="continuePayment(selectedOrder)">
          继续支付
        </button>

        <button class="close-btn" @click="closeModal">关闭</button>
      </view>
    </view>
  </view>
</template>

<script>

export default {
  data() {
    return {
      orders: [], // 存储订单数据
      showModal: false,
      selectedOrder: null,
      userId: null, // 存储从本地获取的 userId
      feePrice: {},
      consultationType:'图文',
      consultationOrderRequest:{},
    };
  },

  onLoad() {
    this.fetchOrders();
  },

  methods: {
    async fetchOrders() {
      // 从本地存储中获取 userInfo
      const userInfo = uni.getStorageSync('userInfo');
      console.log("userInfo:", userInfo ? userInfo.id : '未获取到用户ID');

      // 检查 userInfo 是否存在
      if (!userInfo || !userInfo.id) {
        uni.showToast({
          title: '用户未登录，请先登录',
          icon: 'none',
          success: () => {
            // 跳转到登录页面
            uni.navigateTo({
              url: '/pages/login/login'
            });
          }
        });
        return;
      }

      this.userId = userInfo.id; // 从 userInfo 中提取 id

      try {
        // 发起请求获取订单数据
        const response = await uni.request({
          url: `http://localhost:8080/app/userinquiry/order/${this.userId}`,
          method: 'GET',
        });
        console.log(response[1].data)
        if (response[1].data.code === 200) {
          const result = response[1].data;
          if (result.code === 200) {
            // 筛选“图文问诊”订单
            this.orders = result.data
                .map(order => ({
                  orderId: order.orderId,
                  doctorName: order.doctorName,
                  doctorTitle: order.doctorTitle,
                  doctorAvatar: order.doctorAvatar,
                  description: order.description,
                  consultationTime: order.consultationTime,
                  orderStatus: order.orderStatus,
                  paymentMethod: order.paymentMethod,
                  orderAmount: order.orderAmount,
                  answerContent:order.answerContent
                }));

          } else {
            uni.showToast({
              title: '获取订单失败',
              icon: 'none'
            });
          }
        } else {
          uni.showToast({
            title: '请求失败，请稍后重试',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取订单出错:', error);
        uni.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      }
      console.log(this.orders)
    },


    formatDescription(desc) {
      return desc.length > 50 ? desc.slice(0, 10) + '查看更多' : desc;
    },

    formatTime(time) {
      const date = new Date(time);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: 'numeric',
        day: 'numeric',
        hour: 'numeric',
        minute: 'numeric',
        hour12: false
      }).replace(/\//g, '-'); // 格式化为 2020-3-19 10:06
    },

    getStatusClass(status) {
      switch (status) {
        case '待支付': return 'status-pending';
        case '待回答': return 'status-answering';
        case '已完成': return 'status-done';
        default: return '';
      }
    },

    openOrder(order) {
      this.selectedOrder = order;
      this.showModal = true;
    },

    // 继续支付
    async continuePayment() {
      console.log("absuaoydoiasduoidaj：：：",this.selectedOrder.orderId)
      if (!this.selectedOrder) {
        console.error("selectedOrder 是 undefined，可能被重置了！");
        return;
      }
      console.log("选中的订单ID：", this.selectedOrder.orderId);
      // 先查询支付金额
      await this.fetchConsultationFee();
      // 构造 ConsultationOrderRequest 对象
      this.consultationOrderRequest = {
        // consultationTypes: this.consultationTypes[this.selectedConsultationType],
        orderAmount: this.feePrice,
        userId: this.userId,
        // 其他 ConsultationOrderRequest 属性
        orderId:this.selectedOrder.orderId
      };

      // 显示支付弹窗
      uni.showModal({
        title: '支付确认',
        content: `本次问诊费用：¥${this.feePrice}`,
        confirmText: '去支付',
        success: async (res) => {
          if (res.confirm) {
            this.processAlipayPayment();
          }
        }
      });
    },


    closeModal() {
      this.showModal = false;
      this.selectedOrder = null;
    },
    // 获取支付费用
    async fetchConsultationFee() {
      uni.showLoading({ title: '加载中...' });

      const [err, res] = await uni.request({

        url: `http://localhost:8080/app/userinquiry/getFeeByType/${this.consultationType}`,
        method: 'GET'
      });

      uni.hideLoading();

      if (err) {
        console.error('请求错误:', err);
        uni.showToast({ title: '获取费用失败', icon: 'none' });
        return;
      }

      console.log('支付费用数据:', res);
      console.log(res.data.data)
      if (res.data && res.data.code === 200) {
        this.feePrice = res.data.data.feePrice;  // 赋值给变量，前端页面显示
      } else {
        uni.showToast({ title: '获取费用失败', icon: 'none' });
      }
    },

    // 处理支付宝支付
    async processAlipayPayment(consultationOrderRequest) {
      uni.showLoading({ title: '创建订单...' });

      const [err, res] = await uni.request({
        url: `http://localhost:8080/app/userinquiry/continuePay`,
        method: 'POST',
        data: this.consultationOrderRequest


      });

      uni.hideLoading();

      if (err) {
        console.error('支付请求错误:', err);
        uni.showToast({ title: '失败', icon: 'none' });
        return;
      }
      console.log(res)
      if (res.data.code && res.statusCode === 200) {
        // 获取支付宝支付 URL，跳转到支付页面

        console.log(res.data.msg)
        document.write(res.data.msg)
        document.body.innerHTML = res.data.msg
      } else {
        uni.showToast({ title: '支付失败', icon: 'none' });
      }
    }
  },
};
</script>


<style scoped>
/* 页面背景 */
.consultation-page {
  padding: 20px;
  background-color: #f5f5f5;
}

/* 顶部导航栏 */
.tab-bar {
  display: flex;
  justify-content: space-around;
  margin-bottom: 20px;
}

.tab {
  font-size: 16px;
  color: #666;
}

.active {
  color: #2d82ff;
  border-bottom: 2px solid #2d82ff;
  padding-bottom: 5px;
}

/* 订单列表 */
.order-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.order-item {
  display: flex;
  background-color: #fff;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  cursor: pointer;
}

/* 医生头像 */
.doctor-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}

/* 订单内容 */
.order-content {
  flex: 1;
}

.doctor-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.doctor-name {
  font-size: 16px;
  font-weight: bold;
}

.doctor-title {
  font-size: 14px;
  color: #999;
}

.order-status {
  font-size: 14px;
  margin-bottom: 5px;
}

.order-description {
  font-size: 14px;
  color: #333;
  margin-bottom: 5px;
}

.order-time {
  font-size: 12px;
  color: #999;
}

/* 订单状态颜色 */
.status-pending {
  color: #ff3b30;
}

.status-answering {
  color: #f6a623;
}

.status-done {
  color: #4cd964;
}

/* 订单详情弹窗 */
.order-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-content {
  width: 80%;
  background: white;
  padding: 20px;
  border-radius: 8px;
}

.modal-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 15px;
}

.close-btn {
  margin-top: 15px;
  background: #007bff;
  color: white;
  padding: 8px 15px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}
</style>
